//
//  DocListDataItem.m
//  Personal Passlock
//
//  Created by 杨岑 on 5/12/15.
//  Copyright (c) 2015 杨岑. All rights reserved.
//

#import "DocListDataItem.h"

@implementation DocListDataItem

+ (instancetype)create:(NSMetadataItem *)metadataItem
{
    return [[self alloc] initWith:metadataItem];
}

- (instancetype)initWith:(NSMetadataItem*)metadataItem
{
    self = [super init];
    if (self)
    {
        [self parse:metadataItem];
    }
    return self;
}

- (void)copyFrom:(DocListDataItem *)from
{
    self.metadataItem = from.metadataItem;
    self.filename = from.filename;
    self.name = from.name;
    self.URL = from.URL;
    self.lastModification = from.lastModification;
    self.inConflict = from.inConflict;
    self.isPrimary = from.isPrimary;
    self.percentDownloaded = from.percentDownloaded;
    self.state = from.state;
    self.status = from.status;
}

- (void)parse:(NSMetadataItem*)metadataItem
{
    self.URL = [metadataItem valueForAttribute:NSMetadataItemURLKey];
    self.filename = [metadataItem valueForAttribute:NSMetadataItemFSNameKey];
    //self.name = [metadataItem valueForAttribute:NSMetadataItemDisplayNameKey];
    //if (self.name.length == 0)
    {
        self.name = [self.filename stringByDeletingPathExtension];
    }
    
    self.lastModification = [metadataItem valueForAttribute:NSMetadataItemFSContentChangeDateKey];
    NSNumber* conflict = [metadataItem valueForAttribute:NSMetadataUbiquitousItemHasUnresolvedConflictsKey];
    self.inConflict = conflict.boolValue;
    
    self.percentDownloaded = [self.metadataItem valueForAttribute:NSMetadataUbiquitousItemPercentDownloadedKey];

    NSString* status = [metadataItem valueForAttribute:NSMetadataUbiquitousItemDownloadingStatusKey];
    if ([status isEqualTo:NSMetadataUbiquitousItemDownloadingStatusCurrent])
    {
        self.status = DocumentStatusCurrent;
    }
    else if ([status isEqualTo:NSMetadataUbiquitousItemDownloadingStatusDownloaded])
    {
        self.status = DocumentStatusNotRecent;
    }
    else if ([status isEqualTo:NSMetadataUbiquitousItemDownloadingStatusNotDownloaded])
    {
        self.status = DocumentStatusNotLocal;
    }
    else
    {
        self.status = DocumentStatusUnknown;
    }
}

@end
